/**
 * axios
 */
import axios from 'axios';
import qs from 'qs';
import { ElMessageBox, ElMessage } from 'element-plus';

let messageBoxShow = false;
// 错误信息的处理方法
const errorHandle = res => {
  switch (res.status) {
  case 400:
    // console.log('服务不理解请求的语法')
    ElMessage.error(res.data.message);
    // debugger
    break;
  case 401:
    console.log('（未授权）， 请求要求身份验证身份');
    if (!messageBoxShow) {
      messageBoxShow = true;
      ElMessageBox.prompt('请输入密码登录', 'Tip', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        dangerouslyUseHTMLString: true,
        showClose: false,
        showCancelButton: false,
        closeOnClickModal: false,
        'close-on-press-escape': false,
        'close-on-hash-change': false,
        type: 'warning',
        inputType: 'password',
        'inputValidator': function(val){
          if (val){
            return true;
          }
          return '请输入正确的密码';
        },
        'beforeClose': function (action, instance){
          instance.confirmButtonLoading = true;
          service({
            url: '/login',
            data: instance.inputValue,
            headers: {
              'Content-Type': 'text/plain'
            },
            returnResponse: true,
          }).then(res=>{
            if (res.data.code == 200){
              messageBoxShow = false;
              window.location.reload(true);
            } else {
              instance.validateError = true;
              instance.editorErrorMessage = res.data.message;
            }
          }).finally(()=>{
            instance.confirmButtonLoading = false;
          });

        }
      });
    }
    break;
  case 403:
    if (!messageBoxShow) {
      messageBoxShow = true;
      ElMessageBox.alert('您没有权限访问此页面', '提示', {
        confirmButtonText: '确定',
        type: 'warning'
      }).then(() => {
        ElMessageBox.close();
        // window.location.reload(true)
        messageBoxShow = false;
      });
    }
    
    break;
  case 404:
    console.log('网络请求地址错误');
    break;
  case 500:
    serviceErrorHandle(res);
    break;
  default:
    var msg = '请求错误，请稍后再试';
    if (res.data?.message){
      msg = res.data.message;
    }
    ElMessage.error(msg);
    break;
  }
};

function serviceErrorHandle(res){
  let data = res.data;
  var msg = '请求错误，请稍后再试';
  switch(data.code){
  case 601: // 参数验证错误
    msg = '参数验证错误';
    data.data.forEach && data.data.forEach((m, index)=>{
      msg += `<br/>&nbsp;&nbsp; ${index + 1}.&nbsp;${m}`;
    });
    break;

  default:
    if (data.message) {
      msg = data.message;
    }
    break;
  }

  ElMessage({
    type: 'error',
    dangerouslyUseHTMLString: true,
    message: msg
  });
}

// 统一配置
const service = axios.create({
  setToken: true,
  baseURL: process.env.VUE_APP_BASE_PATH,
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 36000, // request timeout
  method: 'POST',
  headers: {
    'Access-Control-Allow-Origin': '*',
    'Content-Type': 'application/json',
    'X-Requested-With': 'XMLHttpRequest'
  }
});

// 请求拦截
service.interceptors.request.use(config => {
  if (config.headers['Content-Type'].startsWith('application/x-www-form-urlencoded')) {
    if (config.data) {
      config.data = qs.stringify(config.data);
    } else {
      config.data = '';
    }
  }

  // 添加默认参数 axios 中会删除没有data的请求头 Content-Type
  // file://node_modules/axios/lib/adapters/xhr.js
  else if (['post', 'put'].includes(config.method.toLowerCase()) && config.data == undefined){
    config.data = {};
  }
    
  return config;
},
error => Promise.reject(error)
);

const businessErrorCode = [500, 600];

// 响应拦截
service.interceptors.response.use(
  // 成功
  response => {
    if (response.config.returnResponse){ // 不处理结果, 直接返回res
      // if (businessErrorCode.includes(response.data?.code)){
      //   return Promise.reject(response);
      // }
      return response;
    }

    // 错误处理
    if (response.status !== 200 || businessErrorCode.includes(response.data?.code)) {
      errorHandle(response);
      return Promise.reject(response.data);
    }

    // 成功处理
    if (response.config.responseType == 'blob'){
      let blobType = response.data.type;
      if (blobType == 'application/octet-stream'){
        let filename = response.headers.filename;
        if (!filename){
          let h = response.headers['content-disposition'];
          filename = h.substr(h.indexOf('filename=') + 9);
        }
        response.data.name = decodeURI(filename);
      }

    }

    return response.data;
  },
  // 失败
  error => {
    const { response } = error; // ES6解构

    if (response?.config?.returnResponse) { // 不处理结果, 直接返回res
      return Promise.reject(response);
    }
    
    if (response) {
      errorHandle(response);
    } else {
      ElMessage.error('请求中断或者断网了');
      console.error(error);
    }
    return Promise.reject(response);
  }
);
export default service;
